package com.tedu;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class Test1 {
    public Test1(){}
    public Test1(int age){this.age = age;}
    public Test1(String name, int age) {
        this.name = name;
        this.age = age;
    }
    public String name;
    public int age;
    public void code(int a){
        System.out.println(1);
    }
    public void code2(String b){
        System.out.println(2);
    }
}
class X{
    public static void main(String[] args) throws Exception {
        method();//获取Class对象
        method2();//解析.class文件里 的构造方法
        method3();//解析.class文件里 的成员变量
        method4();//解析.class文件里 的成员方法
        method5();//通过反射创建对象
        method6();//设置属性的值并获取
        method7();//执行方法
    }
    private static void method() throws ClassNotFoundException {
        Class c=Test1.class;
        //Class c=new Test1().getClass();
        //Class c=Class.forName("cn.tedu.Test1");
        System.out.println(c.getSimpleName());//获取类名
        System.out.println(c.getName());//获取全路径
        System.out.println(c.getPackage().getName());//获取包名
    }
    private static void method2() throws NoSuchMethodException {
        Class c=Test1.class;
        Constructor[] a=c.getConstructors();
        //System.out.println(a);
        for(Constructor x:a){
            System.out.println(x.getName()+"++");
            Class[] b=x.getParameterTypes();
            System.out.println(Arrays.toString(b)+"~~");
        }
    }
    private static void method3(){
        Class c=Test1.class;
        Field[] a=c.getDeclaredFields();
        for(Field x:a){
            System.out.println(x.getName());
            System.out.println(x.getType().getName());
        }
    }
    private static void method4(){
        Class c=Test1.class;
        Method[] a=c.getDeclaredMethods();
        for(Method x:a){
            System.out.println(x.getName()+"____");
            Class[] b=x.getParameterTypes();
            System.out.println(Arrays.toString(b));
        }
    }
    private static void method5() throws Exception {
        Class c=Test1.class;
        Object o=c.newInstance();
        System.out.println(o);

        Constructor z=c.getConstructor(int.class);
        Object o1=z.newInstance(21);
        System.out.println(o1);
    }
    private static void method6() throws Exception {
        Class c=Test1.class;
        Field f=c.getField("name");
        Object o=c.newInstance();
        f.set(o,"晨晨");
        System.out.println(f.get(o));
    }
    private static void method7() throws Exception {
        Class c=Test1.class;
        Method m=c.getDeclaredMethod("code",int.class);
        Object o=c.newInstance();
        m.invoke(o,100);
    }



}





